package com.kplzj.maptest.map.cc;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Xml;
import android.view.View;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xmlpull.v1.XmlPullParser;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class CustomMapView extends View {
    private List<float[]> pointsList = new ArrayList<>();
    private Paint paint = new Paint();
    private float scale = 10f; // 默认缩放比例为1.0，即100%

    public CustomMapView(Context context, AttributeSet attrs) {
        super(context, attrs);
        parseXmlFile("map3.xml");
    }

    private void parseXmlFile(String fileName) {
        try {
            InputStream inputStream = getContext().getAssets().open(fileName);
            XmlPullParser parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(inputStream, null);

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_TAG && parser.getName().equals("Pt")) {
                    float x = Float.parseFloat(parser.getAttributeValue(null, "x"))  * scale;
                    float y = Float.parseFloat(parser.getAttributeValue(null, "y")) * scale;
                    pointsList.add(new float[]{x, y});
                }
                eventType = parser.next();
            }
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setColor(Color.RED);
        paint.setStrokeWidth(5);

        // Convert negative coordinates to positive values and scale them to fit the screen
        float minX = Float.MAX_VALUE;
        float minY = Float.MAX_VALUE;
        for (float[] point : pointsList) {
            if (point[0] < minX) minX = point[0];
            if (point[1] < minY) minY = point[1];
        }
        float offsetX = minX < 0 ? -minX : 0;
        float offsetY = minY < 0 ? -minY : 0;
        // Draw the points
        for (float[] point : pointsList) {
            float x = point[0] + offsetX;
            float y = point[1] + offsetY;
            canvas.drawPoint(x, y, paint);
        }
    }
}
